package com.wh.springboot.config.Interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.wh.springboot.common.Constants;
import com.wh.springboot.common.entity.User;
import com.wh.springboot.exception.ServiceException;
import com.wh.springboot.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 执行认证
        //查看token是否是空字符串
        if (StrUtil.isBlank(token)) {
            throw new ServiceException(Constants.Status_401, "无token，请重新登录");
        }
        // 获取 token 中的 user id
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch (JWTDecodeException j) {
            throw new ServiceException(Constants.Status_401, "token验证失败，请重新登录");
        }
        //验证这个用户信息是否存在
        //根据token的userId查询数据库，查询用户数据
        //查不出来，说明这个用户不存在，这个token不合法
        User user = userService.getById(userId);
        if (user == null) {
            throw new ServiceException(Constants.Status_401, "用户不存在，请重新登录");
        }
        // 用户密码加签 验证 token
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token);//验证 token
        } catch (JWTVerificationException e) {
            throw new ServiceException(Constants.Status_401, "token验证失败，请重新登录");
        }
        return true;
    }
}
